<template>
  <el-dialog :visible.sync="visible" title="修改密码" v-if="visible">
    <el-form :model="formData" label-position="right" label-width="80px" :rules="rules" ref="formData">
      <el-form-item label="用户名">
        <el-input placeholder="请输入用户名" readonly v-model="formData.username"/>
      </el-form-item>
      <el-form-item label="原密码" prop="oldPwd">
        <el-input type="password" placeholder="请输入原密码" v-model="formData.oldPwd"/>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input type="password" placeholder="请输入新密码" v-model="formData.password"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPwd">
        <el-input type="password" placeholder="请再次输入密码" v-model="formData.confirmPwd"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="update">提交</el-button>
        <el-button type="warning" @click="visible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
const formData = {
  userId: '',
  username: '',
  oldPwd: '',
  password: '',
  confirmPwd: ''
}
export default {
  name: 'UserinfoPassword',
  data () {
    return {
      visible: false,
      formData: {
        ...formData
      },
      rules: {
        oldPwd: [{
          required: true,
          message: '请输入原密码',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '请输入新密码',
          trigger: 'blur'
        }],
        confirmPwd: [{
          required: true,
          message: '请再次输入密码',
          trigger: 'blur'
        }, {
          validator: (rule, value, callback) => {
            if (value === this.formData.password) {
              callback()// 验证通过则放行
            } else {
              callback(new Error('两次密码不一致'))
            }
          },
          trigger: 'blur'
        }]
      },
      loginId: ''
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$http.get('userinfo/info').then(({ data }) => {
        this.formData = {
          ...formData,
          username: data.username,
          userId: data.userId
        }
      })
    },
    update () {
      this.$refs.formData.validate(valid => {
        if (valid) {
          this.$http.post('userinfo/password', this.formData).then(() => {
            this.$alert('密码修改成功，请重新登录', { type: 'success' }).then(() => {
              this.visible = false
              this.$emit('onCloseDialog')
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
